package com.sam.controller;

import com.google.common.collect.Maps;
import com.sam.schedule.ScheduleServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping(value = "/schedule")
public class ScheduleController {

    @Autowired
    private ScheduleServiceImpl scheduleService;

    @RequestMapping(value = "/start", method = RequestMethod.GET)
    public String startJob(){
        return scheduleService.startJob();
    }

    @RequestMapping(value = "/stop", method = RequestMethod.GET)
    public String stopJob() {
        return scheduleService.stopJob();
    }

    @RequestMapping(value = "/restart", method = RequestMethod.GET)
    public String reStartJob() {
        return scheduleService.reStartJob();
    }

    @RequestMapping(value = "/status", method = RequestMethod.GET)
    public Map status() {
        Map<String, Integer> oldMap = scheduleService.query();

        Map<String, String> filterMap = Maps.newHashMap();
        filterMap.remove("batchId");
        Map<String, Object> resultMap = Maps.newTreeMap();

        oldMap.forEach((k,v) -> {
            if("batchId".equals(k)){
                resultMap.put(k,v);
            }
            if("status".equals(k)){
                resultMap.put(k,statusString(v));
            }
            if(k.startsWith("job")){
                filterMap.put(k, statusString(v));
            }
        });
        resultMap.put("worker", filterMap);
        return resultMap;
    }

    private String statusString(int code) {
        String s = "未知";
        switch (code) {
            case -1:
                s = "失败";
                break;
            case 0:
                s = "未启动";
                break;
            case 1:
                s = "成功";
                break;
            default :
                s = "运行中";
                break;
        }
        return s;
    }

}
